<template>
	<body-wrap isFlex>
		<!--60 查看专家回复支付订单，61 线下预约订单，62 线上一对一语音咨询订单，63 用户购买的咨询包，-->
		<template v-if="orderInfo.orderType==61 || orderInfo.orderType==62">
			<view class="orderItemBox">
				<view class="title">专家信息：</view>
				<view class="infoBox">
					<view class="imgbox">
						<cm-image :src="orderInfo.product.teacherId.selfAvatar || orderInfo.product.teacherId.avatar"/>
					</view>
					<view class="top-con">
						<view class="name">
						{{orderInfo.product.teacherId.name || orderInfo.product.teacherId.nickname}} 
						<text class="bzhi">专家</text></view>
						<view class="intro">
							{{orderInfo.product.teacherId.company}} | {{orderInfo.product.teacherId.industry}} | {{orderInfo.product.teacherId.jobs}}
						</view>
					</view>
				</view>
			</view>
			<view class="orderItemBox">
				<view class="title">问题描述：</view>
				<view class="qams">{{orderInfo.additionals.question_describe}}</view>
			</view>
		</template>
		<template v-else>
			<view class="linkList">
				<view class="item">
					<label class="name">商品名称</label>
					<view class="lwb">{{orderInfo.name}}</view>
				
				</view>
			</view>
		</template>
		
		
		<view class="linkList">
			<view class="item">
				<label class="name">商品价格</label>
				<view class="lwb">￥<text class="itprice">{{orderInfo.price}}</text></view>
				
			</view>
			<view class="item">
				<label class="name">优惠券</label>
				<view class="lwb">无优惠券可用</view>
				<view class="icon"><cm-image src="static/images/sjt.png"/></view>
			</view>
		</view>
		<view class="linkList" v-if="orderInfo.orderType!=63">
			<view class="item" @click="openPop">
				<label class="name">咨询包</label>
				<view class="lwb" v-if="couponsTotal>0">{{couponsTotal}}个咨询包可用</view>
				<view class="lwb" v-else>无咨询包可用</view>
				<view class="icon"><cm-image src="static/images/sjt.png"/></view>
			</view>
		</view>
		
		<template #footer>
			<view class="ftopbox">
				<view class="price">合计：
					<text class="fh">￥
						<text class="num" v-if="zxbId">0</text>
						<text class="num" v-else>{{orderInfo.price}}</text>
					</text>
				</view>
				<view class="btn">
					<view class="myBtn" @click="formSumbit">提交订单</view>
				</view>
			</view>
		</template>
		
		<uni-popup ref="popup" v-if="orderInfo.orderType!=63">
			<view class="zxbbox">
				<coupon ref="cpnRef" @change="radioChange" @reqOver="getCouponNumber"/>
				<view class="scBtn">
					<div class="myBtn" @click="comfirm">确定使用</div>
				</view>
			</view>
		</uni-popup>
		
	</body-wrap>
</template>

<script>
	import {defineComponent,reactive,toRefs,onMounted,getCurrentInstance,computed} from 'vue'
	import {onLoad,onShow} from '@dcloudio/uni-app'
	import { useStore } from 'vuex'
	import bodyWrap from "@/components/bodyWrap/index.vue"
	import cmImage from "@/components/cmImage/index.vue"
	import coupon from "./components/coupon.vue"
	import {toast,dateAdd} from '@/utils/common.js'
	import {addOrder,getOrderList,packageUseCount} from "@/api/consult.js"
	import {createMeeting,getMeetingDetail,sendMessage} from '@/api/qy-wechat-api.js'
	import {TEN_USERID,CORPID,AGENTID} from "@/utils/config.js"
	export default defineComponent({
		components:{
			bodyWrap,
			cmImage,
			coupon
		},
		props:{
		
		},
		setup(props,context) {
			const store = useStore()
			const {proxy} = getCurrentInstance()
			
			const state = reactive({
				userInfo:computed(()=>store.state.base.userInfo),
				backUrl:computed(()=>store.state.base.backUrl),
				orderInfo:computed(()=>store.state.base.orderInfo),
				zxbId:'',
				couponsTotal:0
			})
			
			onMounted(()=>{
				console.log("订单信息：",state.orderInfo)
				if(!state.orderInfo.product){
					return toast('商品信息不存在！')
				}
				
			})
			
			const openPop = ()=>{
				if(state.couponsTotal == 0){
					return
				}
				proxy.$refs.popup.open('bottom')
			}
			
			const radioChange =(id)=> {
				console.log("********radioChange:",id);
				state.zxbId = id
			}
			
			
			const comfirm = ()=>{
				if(!state.zxbId){
					return toast("请选择咨询包")
				}else if(!proxy.$refs.cpnRef.checkUseForTeacher(state.zxbId,state.orderInfo.product.teacherId._id)){ // 公司咨询时，检查购买咨询包公司的服务专家是不是该项服务的专家
					//return toast("该专家不能使用该咨询包！")
					uni.showModal({
						title: '提示',
						content: '该专家不能使用该咨询包，请选择其他咨询包！',
						showCancel:false,
						success:  (res)=> {
							state.zxbId = ''
						}
					});
					return
				}
				proxy.$refs.popup.close()
			}
			const getCouponNumber = (num)=>{
				state.couponsTotal = num
			}
			
			const formSumbit = async ()=>{
				const params = {
					productId:state.orderInfo.productId, // 商品id
					oldPrice:state.orderInfo.price,  // 商品源价格
					price:state.orderInfo.price, // 商品实际价格（折扣价）
					money:state.orderInfo.price, //微信或者支付宝等第三方平台实际支付的金额
					balanceMoney:0, // 余额支付部分
					payType:3,  // 支付类型  1余额支付，2支付宝，3微信，4为微信支付+余额抵扣,5线下支付，6咨询包抵扣
					sellerId:state.orderInfo.sellerId,  // 卖家id
					userId:state.orderInfo.companyId?null:state.userInfo._id, // 买家id
					openid:state.userInfo.openid, // 买家openid
					quantity:1, // 数量
					orderType:state.orderInfo.orderType,
					status:0, // 订单状态：0待付款、1为已完成,2已经取消（删除）
					additionals:state.orderInfo.additionals, // 预约咨询才会有
					startTime:state.orderInfo.startTime || '',// 预约咨询才会有
					endTime:state.orderInfo.endTime || '',// 预约咨询才会有
					companyId:state.orderInfo.companyId,
					operatorId:state.orderInfo.operatorId
				}
				if(state.zxbId){ // 使用咨询包
					params.money = 0
					params.status = 1
					params.payType = 6
					params.couponOrderId = state.zxbId
				}
				if(state.orderInfo.orderType==63){ // 咨询包购买：计算有效期
					// params.startTime = new Date() // 当前时间
					// params.endTime = dateAdd(state.orderInfo.product.expires)
					if(state.orderInfo.product.type==2){ // 限时咨询包
						params.startTime = new Date() // 当前时间
						params.endTime = dateAdd(state.orderInfo.product.limitTime)
					}else if(state.orderInfo.product.type==3){ // 限次咨询包
						//计算咨询包可有效期（即超过这个时间了，即使咨询包没有用完的，也不能使用了）
						if(state.orderInfo.product.expires){ 
							params.startTime = new Date() // 当前时间
							params.endTime = dateAdd(state.orderInfo.product.expires)
						}
					}
				}
				if(state.orderInfo.orderType==62){ // 一对一语音咨询下单
					const startTime_timestamp = Math.ceil(new Date(params.startTime) / 1000)  // 开始时间时间戳：十位数时间戳
					const endTime_timestamp = Math.ceil(new Date(params.endTime) / 1000)  // 结束时间时间戳：十位数时间戳
					// 创建腾讯会议
					const res = await createMeeting({
						admin_userid:TEN_USERID,// 会议管理员userid
						title:state.orderInfo.product.title, // 会议的标题，最多支持40个字节或者20个utf8字符
						meeting_start:startTime_timestamp, // 会议开始时间的unix时间戳(10位数的时间戳)。需大于当前时间
						meeting_duration:endTime_timestamp-startTime_timestamp, // 会议持续时间单位秒，最小300秒
						agentId:AGENTID,
						corpid:CORPID,
						invitees:{ // 会议参与人员（必须包括管理者）
							userid: [TEN_USERID]
						}
					})
					if(res.code!=200){
						return toast('腾讯会议创建失败')
					}
					params.additionals.meetingInfo=res.data
				}
				console.log("params:",params)

				const res = await addOrder(params)
				if(res.code == 200){
					if(res.data.orderInfo.status == 1){
						toast('下单成功')
						resultBack()
					}else if(res.data.payInfo){
						//toast('下单成功，等待支付')
						wxPay(res.data.payInfo)
					}
				}else{
					toast('下单失败')
				}
				
			}
			// 调起微信支付
			const wxPay = (params)=>{
				uni.requestPayment({
				    provider: "wxpay", 
				    timeStamp: params.timeStamp,        // 时间戳（单位：秒）
				    nonceStr:params.nonceStr,
				    package:params.package,
				    signType:params.signType,
				    paySign:params.paySign,
				    success:ret=> {
						if(state.orderInfo.orderType==63 && state.orderInfo.buyType==2){ // 为公司购买咨询包
							uni.showModal({
								title: '提示',
								confirmText:'立即邀请',
								content: `您已经成功为${state.orderInfo.companyName}购买了咨询包，可以邀请人员加入公司，加入成功后，被邀请人即可免费使用咨询包！`,
								success: function (res) {
									if (res.confirm) {
										uni.reLaunch({
											url:`/pages/home/package/qrCode?companyId=${state.orderInfo.companyId}&name=${state.orderInfo.companyName}`
										})
									} else if (res.cancel) {
										resultBack()
									}
								}
							});
						}else{
							toast('支付成功')
							resultBack()
						}
					},
				    fail:err=> {
						//showModal(JSON.stringify(err))
						const errMsg = JSON.stringify(err)
						if(errMsg.indexOf('cancel')>-1){
							uni.showToast({
								title: '取消支付',
								icon:'none'
							});
							resultBack()
						}else{
							toast(errMsg)
						}
					}
				})
			}
			
			const resultBack = ()=>{
				setTimeout(()=>{
					if(state.backUrl){
						uni.redirectTo({
							url:state.backUrl
						})
					}else{
						uni.navigateBack({delta:1}) // 返回上一页
					}
				},2000)
			}
			
			return {
				...toRefs(state),
				openPop,
				radioChange,
				comfirm,
				formSumbit,
				getCouponNumber
			}
		}
	})
</script>

<style lang="scss" scoped>
	.orderItemBox{
		background-color: #fff;
		padding: 20rpx;
		box-shadow: 0 0 5px #eee;
		&.orderItemBox{
			margin-top: 20rpx;
		}
		.title{
			font-size: 30rpx;
			color: #333;
			font-weight: 700;
			padding: 0 0 20rpx 0;
		}
		.qams{
			font-size: 28rpx;
			color: #999;
			line-height: 46rpx;
		}
	}
	.infoBox{
		display: flex;
		.imgbox{
			width: 100rpx;
			height: 100rpx;
			border-radius: 50%;
			overflow: hidden;
			flex-shrink: 0;
		}
		.top-con{
			padding: 0 0 0 20rpx;
			flex-shrink: 0;
			height: 0;
			.name{
				display: flex;
				height: 50rpx;
				align-items: center;
				font-size: 30rpx;
				font-weight: bold;
				padding: 0;
				margin: 0;
				.bzhi{
					background-color: #ff1120;
					font-size: 22rpx;
					color: #fff;
					padding: 0 8rpx;
					border-radius: 5rpx;
				}
			}
			.intro{
				color: #999;
				font-size: 28rpx;
				height: 50rpx;
				line-height: 50rpx;
				width: 100%;
				white-space: nowrap;
				text-overflow: ellipsis;
				overflow: hidden;
				word-break: break-all;
			}
		}
	}
	.ftopbox{
		display: flex;
		height: 100rpx;
		align-items: center;
		background-color: #fff;
		box-shadow: 0 0 5px #eee;
		padding: 0 20rpx;
		.price{
			flex: 1;
			font-size: 30rpx;
			.fh{
				color: #ff1120;
				.num{
					font-size: 36rpx;
					font-weight: 600;
				}
			}
		}
		.btn{
			width: 200rpx;
		}
	}
	.linkList{
		.item{
			display: flex;
			align-items: center;
			height: 80rpx;
			box-shadow: 0 0 5px #eee;
			padding: 0 20rpx;
			font-size: 30rpx;
			background: #fff;
			&.item{
				margin-top: 20rpx;
			}
			.name{
				flex: 1;
				flex-shrink: 0;
				color: #333;
			}
			.lwb{
				color: #999;
				font-size: 28rpx;
				.itprice{
					color: #efc757;
					font-size: 40rpx;
				}
			}
			.icon{
				width: 50rpx;
				height: 50rpx;
				overflow: hidden;
				opacity: 0.5;
				transform: rotate(90deg);
				-webkit-transform: rotate(90deg); 
			}
		}
	}
	.zxbbox{
		display: flex;
		flex-flow: column;
		min-height:500rpx;
		background: #fff;
		border-top-left-radius:30rpx ;
		border-top-right-radius:30rpx ;
		padding: 0;
		background-color: #f7f8fa;
		.zxbmain{
			flex: 1;
			flex-shrink: 0;
			padding: 20rpx;
			padding-top: 40rpx;
			.zxbInfo{
				display: flex;
				border-radius: 15rpx;
				box-shadow: 0 0 4px rgba(0, 0, 0, 0.1);
				background: #fff;
				padding: 20rpx;
				&+.zxbInfo{
					margin-top: 20rpx;
				}
				.xxbox{
					flex: 1;
					flex-shrink: 0;
					line-height: 50rpx;
					.name{
						font-size: 30rpx;
						font-weight: bold;
					}
					.express{
						font-size: 28rpx;
						color: #999;
						padding: 0;
					}
				}
				.rdbox{
					display: flex;
					align-items: center;
					padding: 0 0 0 15rpx;
				}
			}
		}
		.scBtn{
			background-color: #fff;
			padding: 20rpx 30rpx;
		}
	}
	
	
</style>
